<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\api\controller;

/**
 * 栏目管理
 */
class Mp extends BaseController
{

    /**
     * 当前操作数据库
     */
    public $table = 'CmsCarWorks';
    public $tablePay = 'CmsCarPay';
    public $tableSearch = 'CmsCarSearch';
    public $tableScan = 'CmsCarScan';
    public $pageSize = 5;
    public  $item = ["机油保养","机修","美容","其他","全部"];
    public  $payment = ["已付款","未付款","未付全款"];
    const DT_ROOT = 'https://hmx.letukeji.cn';
    public $scan_num_for_free = 1000;

    /**
     * 栏目管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        $this->title = '汽车';
        echo "222";
        //$this->_page($this->table, true);

        //$this->fetch();
    }

    public function loadf(){
        $file=$this->request.get("file");

    }

    /**
     * 添加项目
     */
    public function add()
    {
        if ($this->request->isGet()) {
            $this->_form($this->table, 'form');
        } else {


            $repair=$this->request->post('repair');
            $img=$this->request->post('img');

            if($img!="" && $img!=[]){
                for($i=0; $i<count($img); $i++) {
                    //$this->error($value);
                    $img[$i] = "https://hmx.letukeji.cn/" . $img[$i];
                }
            }
            $imgStr = implode(",", $img);


            $repairs = implode(',',$repair);
            $update = [
                'number' => $this->request->post('number'),
                "mileage" => $this->request->post('mileage'),
                "remarks" => $this->request->post('remarks'),
                'repair' => $repairs,
                'content' => $this->request->post('content'),
                'img' => $imgStr,
                'status' => $this->request->post('status'),
                'paid' => $this->request->post('paid'),
                'total' =>$this->request->post('total'),
                'start_at'=>date('Y-m-d', time()),
                'app_id'=>$this->request->post('openid')
            ];
            if(!$update['status']) $update['status'] = 0;
            if(!$update['paid']) $update['paid'] = 0;
            if ($this->app->db->name($this->table)->insert($update) !== false) {
                $this->success('添加成功！');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    //编辑工单
    public function edit()
    {
        if ($this->request->isGet()) {
            $this->_form($this->table, 'form');
        } else {

            $repair=$this->request->post('repair');
            $img=$this->request->post('img');

            if($img!="" && $img!=[]){
                for($i=0; $i<count($img); $i++) {
                    //$this->error($value);
                    if(strpos($img[$i], "http")!==0){
                        $img[$i] = "https://hmx.letukeji.cn/" . $img[$i];
                    }
                }
            }
            $imgStr = implode(",", $img);

            $repairs = implode(',',$repair);
            $update = [
                'number' => $this->request->post('number'),
                "mileage" => $this->request->post('mileage'),
                "remarks" => $this->request->post('remarks'),
                'repair' => $repairs,
                'content' => $this->request->post('content'),
                'img' => $imgStr,
                'status' => $this->request->post('status'),
                'paid' => $this->request->post('paid'),
                'total' =>$this->request->post('total'),
                'start_at'=>date('Y-m-d', time()),
            ];

            $app_id=$this->request->post('openid');
            $id =$this->request->post('id');
            $map = ["app_id"=>$app_id, "id"=>$id];
            if ($this->app->db->name($this->table)->where($map)->update($update) !== false) {
                $this->success('修改成功！'.$this->app->db->name($this->table)->getLastSql());
            } else {
                $this->error('修改失败，请稍候再试！');
            }
        }
    }


    public function uploadimg()
    {

//        $this->error(1, $_FILES);

        //$file =$this->app->request->file('img0');
        $file = $_FILES['img0'];
       // $this->error($file);
        if ($file) {
            $info = $file->move('public/upload/weixin/');
            if ($info) {
                $file = $info->getSaveName();
                $res = ['errCode'=>0,'errMsg'=>'图片上传成功','file'=>$file];

                return json($res);
            }
        }

    }

    public function  addImg() {

        //$code = $_FILES['file'];//获取小程序传来的文件
//        $this->erro($_FILES["file"]);
        // return $_FILES['file']['type'];
        // 判断是否是post提交
       // $this->error($code);
        if(is_uploaded_file($_FILES['file']['tmp_name'])) {

            //临时文件
            $uploaded_file = $_FILES['file']['tmp_name'];

            // return $uploaded_file;
            // 允许的图片类型
            $judge_img = array("image/gif","image/pjpeg","image/jpeg","image/png","image/jpg");
            // 允许的视频类型
            $judge_vid = array("video/mp4");
            // 判断是图片还是视频
            if(in_array($_FILES['file']['type'],$judge_img)) {
                // 换算字节  1M = 1024KB;1KB = 1000bt;
                if($_FILES["file"]["size"] > 1024000) {
                    // 图片过大
                    $arr = ['status' => 2];
                    return $arr;
                }
                // 图片的路径
                //$user_path = DT_ROOT."/upload/img/";
                //$this->error(DT_ROOT);
                $user_path = "upload_file/upload/img/";
            }else if(in_array($_FILES['file']['type'],$judge_vid)) {
                if($_FILES["file"]["size"] > 2048*1000) {
                    // 视频过大
                    $arr = ['status' => 2];
                    return $arr;
                }
                // 视频的路径
                $user_path = DT_ROOT."/upload/video/";
            }else {
                // 格式错误
                $arr = ['status' => 1];
                return $arr;
            }
            $file_true_name = $_FILES['file']['name'];
            $move_to_file = $user_path.time()."-".date("Y-m-d").substr($file_true_name,strrpos($file_true_name,"."));
            if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {
                // 上传成功
                $arr = ['status' => 3, 'url' => $move_to_file];
                //$this->error($arr);
                return json($arr);
            } else {
                // 上传失败网络错误，请重新上传
                $arr = ['status' => 4];
                return json($arr);
            }
        } else {
            // 上传方式错误
            $arr = ['status' => 6];
            return json($arr);
        }
    }

    /**
     * 添加项目
     */
    public function setCarUser()
    {

            $pid=$this->request->post('pid');

            // 用户信息验证
            $map = ['pid' =>$pid, 'is_deleted' => '0'];
            $user = $this->app->db->name('CmsCarUser')->where($map)->order('id desc')->find();
            if(!$user){
                $update = [
                    'pid' => $this->request->post('pid'),
                    "nickname" => $this->request->post('name'),
                    "headimg" => $this->request->post('img'),
                ];
                if ($this->app->db->name("CmsCarUser")->insert($update) !== false) {
                    $this->success('添加成功！', $update);
                }
                $this->error('添加失败，请稍候再试！', $update);
            }

            if ($user['status']!=1) {
                $this->error('用户被禁用，请联系管理员!', $user);
            }

            $this->app->db->name('CmsCarUser')->where(['pid' => $user['pid']])->update([
                'login_at'  => $this->app->db->raw('now()'),
                'login_num' => $this->app->db->raw('login_num+1'),
            ]);
            $this->success('登录成功！', $user);

    }

    /**
     * 查询
     */
    public function queryInfo()
    {
        if ($this->request->isGet()) {
            $this->verify = false;
            $this->_form($this->table, 'form');
        } else {
            $this->openid = $this->request->post('openid');
            $this->id = $this->request->post('id');
            $map = ["id" =>$this->id, "app_id"=>$this->openid];
            $query = $this->app->db->name('CmsCarWorks')
               ->where($map)
                ->order('id desc')->find();
            $this->success("200", $query);
        }
    }

    /**
     * 查询
     */
    public function queryList()
    {
        $map = ['app_id' => $this->request->post('openid')];
        $this->number=$this->request->post('number');
        $this->repair=$this->request->post('repair');
        $this->status=$this->request->post('status');
        $this->start_at=$this->request->post('start_at');
        $this->end_at = date('Y-m-d H:i:s',time());

        //将最近的搜索关键字进行记录
        $map2 = ['openid' => $this->request->post('openid')];
        if($this->number){
            $res = $this->app->db->name('CmsCarSearch')->where($map2)->order("id desc")->find();
            if(!$res || $res['number']!=$this->number){
                $data = [
                    "number"=>$this->number,
                    "openid"=>$this->request->post('openid'),
                    "search_time"=>time()
                ];
                $this->app->db->name('CmsCarSearch')->save($data);
            }
        }

        $this->page= intval($this->request->post('page',1));
        $this->offset = ($this->page-1)*$this->pageSize;
        if($this->start_at==="0"){
            $this->start_at=date("Y-m-d H:i:s",strtotime("-1weeks",strtotime($this->end_at)));
           // $this->error($this->start_at);
        }else if($this->start_at==="1"){
            $this->start_at=date("Y-m-d H:i:s",strtotime("-1months",strtotime($this->end_at)));
            //$this->error($this->start_at);
        }else if($this->start_at==="2") {
            $this->start_at = date("Y-m-d H:i:s", strtotime("-1years", strtotime($this->end_at)));
        }else if($this->start_at==="3") {
            $this->start_at = date("Y-m-d H:i:s", strtotime("-3years", strtotime($this->end_at)));
            //$this->end_at = date("Y-m-d H:i:s", strtotime("-1years", strtotime($this->end_at)));
        }else{
            // $this->error($this->start_at);
            $this->start_at = date("Y-m-d H:i:s", strtotime("-3years", strtotime($this->end_at)));
        }
        if($this->status==="0" || $this->status==="1" || $this->status==="2"){
            $map['status'] = $this->status;
        }
        $query =$this->app->db->name('CmsCarWorks')
            ->where($map);
        if($this->number){
            $query = $query->whereLike("number","%".$this->number."%");
        }
        if($this->repair && $this->repair<4){
            $query = $query->whereLike("repair","%".$this->repair."%");
        }
        if($this->start_at){
            $query = $query->whereBetweenTime(" start_at",$this->start_at,$this->end_at);
        }


        $total = $query->count();
        $totalPage = ceil($total*1.0/$this->pageSize);

        $query =$query->order('id desc')->limit($this->offset,$this->pageSize)->select()->toArray();
        for($i=0; $i<count($query); $i++){
            $query[$i]['item'] = $this->getItems($query[$i]['repair']);
            $query[$i]['pay'] = $this->payment[$query[$i]['status']];
            if($query[$i]['status']==2){
                $query[$i]['amount'] = $query[$i]['paid']."/".$query[$i]['total'];
                //$query[$i]['amount'] = ($query[$i]['total']-$query[$i]['paid'])."/".$query[$i]['total'];
            }else if($query[$i]['status']==1){
                $query[$i]['amount'] = $query[$i]['total'];
            } else{
                $query[$i]['amount'] = $query[$i]['total'];
            }
        }
        $this->success($this->app->db->name('CmsCarWorks')->getLastSql(),array("list"=>$query,"totalPage"=>$totalPage));
    }

    public function getItems($items){
        $arr = explode(",", $items);
        $res = array();
        for($i=0; $i<count($arr); $i++){
            $res[] = $this->item[$arr[$i]];
        }
        return join(",", $res);
    }

    public function setUpdate(){
        if ($this->request->isGet()) {
             $this->_form($this->table, 'form');
         } else {
             $id=$this->request->post('id');
             $map = array("id" => $id);
             $update = [
                 'cost' =>$this->request->post('cost'),
                 'explain' =>$this->request->post('cost')
             ];
             if ($this->app->db->name($this->table)->where($map)->update($update) !== false) {
                 $this->success('录入成功！');
             } else {
                 $this->error('录入失败，请稍候再试！');
             }
         }
     }

    public function getOpenIds(){

        $appid=$this->request->get("appid");
        $secret=$this->request->get("secret");
        $grant_type=$this->request->get("grant_type");
        $jgs_code=$this->request->get("js_code");
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=". $secret."&js_code=".$jgs_code."&grant_type=authorization_code";
        //$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxffaa50953eea7e25&secret=186388df44213b4183ef670e8d914ca1&js_code=043HYz0w3Nuo7V2g6V0w3lWjLy4HYz0k&grant_type=authorization_code';
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid="wxffaa50953eea7e25"&secret="186388df44213b4183ef670e8d914ca1"&js_code="043HYz0w3Nuo7V2g6V0w3lWjLy4HYz0k"&grant_type=authorization_code"
//        $result =parent::http_get($url);
//        $data_info=json_decode($result,true);
//        $this->_json['code']=self::CODE_SUCC;
//        $this->_json['msg']=self::MSG_SUCC;
//        $this->_json['data']=$data_info;
//        $this->error($data_info);
//        $this->y_view($this->_json);

        $weixin=file_get_contents($url);//通过code换取网页授权access_token
        $jsondecode=json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
       // $this->error($array);
        $openid = $array['openid'];//输出openid

         return $openid;

    }

    //货款管理
    public function addPay()
    {
        if ($this->request->isPost()) {
            $update = [
                'supplier' => $this->request->post('supplier'),
                "total" => $this->request->post('total'),
                "note" => $this->request->post('note'),
                'start_at'=>$this->request->post('start_at'),
                'openid'=>$this->request->post('openid')
            ];
            if ($this->app->db->name($this->tablePay)->insert($update) !== false) {
                $this->success('添加成功！');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
        $this->error('非法操作！');
    }

    public function getPay()
    {
        $id = $this->request->post('id');
        $openid = $this->request->post('openid');
        $map = array("id"=>$id,"openid"=>$openid);
        $pay = $this->app->db->name($this->tablePay)->where($map)->find();
        if ( $pay !== false) {
            $this->success('操作成功！', $pay);
        } else {
            $this->error('操作失败，请稍候再试！');
        }
    }

    public function editPay()
    {
        if ($this->request->isPost()) {
            $update = [
                'supplier' => $this->request->post('supplier'),
                "total" => $this->request->post('total'),
                "note" => $this->request->post('note'),
                'start_at'=>$this->request->post('start_at'),
            ];
            $map = array("id"=>$this->request->post("id"));
            if ($this->app->db->name($this->tablePay)->where($map)->update($update) !== false) {
                $this->success('修改成功！');
            } else {
                $this->error('修改失败，请稍候再试！');
            }
        }
        $this->error('非法操作！');
    }

    public function searchPay()
    {
        $this->openid=$this->request->post('openid');
        $this->supplier=$this->request->post('supplier');
        $this->start_at=$this->request->post('start_at');
        $this->end_at = date('Y-m-d H:i:s',time());
        $map = ['openid' => $this->openid ];

        if($this->start_at==="0"){
            $this->start_at=date("Y-m-d H:i:s",strtotime("-1weeks",strtotime($this->end_at)));
            // $this->error($this->start_at);
        }else if($this->start_at==="1"){
            $this->start_at=date("Y-m-d H:i:s",strtotime("-1months",strtotime($this->end_at)));
            //$this->error($this->start_at);
        }else if($this->start_at==="2") {
            $this->start_at = date("Y-m-d H:i:s", strtotime("-1years", strtotime($this->end_at)));
        }else if($this->start_at==="3") {
            $this->start_at = date("Y-m-d H:i:s", strtotime("-3years", strtotime($this->end_at)));
            //$this->end_at = date("Y-m-d H:i:s", strtotime("-1years", strtotime($this->end_at)));
        }else{
            // $this->error($this->start_at);
            $this->start_at = date("Y-m-d H:i:s", strtotime("-3years", strtotime($this->end_at)));
        }

        $this->page= intval($this->request->post('page',1));
        $this->offset = ($this->page-1)*$this->pageSize;
        $query =$this->app->db->name('CmsCarPay')
            ->where($map);

        if($this->supplier){
            $query = $query->whereLike("supplier","%".$this->supplier."%");
        }
        if($this->start_at){
            $query = $query->whereBetweenTime(" start_at",$this->start_at,$this->end_at);
        }

        $total = $query->count();
        $totalPage = ceil($total*1.0/$this->pageSize);
        $query = $query->order('id desc')->limit($this->offset,$this->pageSize)->select()->toArray();
        $this->success($this->app->db->name('CmsCarPay')->getLastSql(),array("list"=>$query,"totalPage"=>$totalPage));
    }

    public function getSearchNumbers()
    {
        $this->openid=$this->request->post('openid');
        $map = ["openid"=>$this->openid];
        $query =$this->app->db->name($this->tableSearch)
            ->where($map)->order("id desc")->limit(0,3)->select();
        $numbers = [];
        for($i=0; $i<count($query); $i++){
            $numbers[] = $query[$i]['number'];
        }
        $this->success("200", $numbers);
    }

    public function getLeftScanNum(){
        //返回最近3个扫描的车牌号，剩余扫描次数
        $this->openid=$this->request->post('openid');
        $total = $this->app->db->name($this->tableScan)->where(["openid"=>$this->openid])->count();
        $left_num = $this->scan_num_for_free-$total;
        $left_num = $left_num<0?0:$left_num;
        $this->success('200！',$left_num);
    }

    public function addScan(){
        $update = [
            'number' => $this->request->post('number'),
            'openid'=>$this->request->post('openid'),
            'scan_time'=>time(),
        ];
        if ($this->app->db->name($this->tableScan)->insert($update) !== false) {
            $total = $this->app->db->name($this->tableScan)->where(["openid"=>$update['openid']])->count();
            $this->success('添加成功！', $this->scan_num_for_free-$total);
        } else {
            $this->error('添加失败，请稍候再试！');
        }
    }

}
